<template>
  <div class="knowledge-type-navigation">
    <div class="navigation-header">
      <button 
        class="new-category-btn" 
        @click="openAddModal"
        :disabled="loading"
      >
        <span class="btn-icon">➕</span>
        <span class="btn-text">新建分类</span>
      </button>
    </div>
    
    <div class="type-grid">
      <!-- 全部分类卡片 -->
      <div 
        class="type-card" 
        :class="{ active: selectedTypeId === null }"
        @click="selectType(null)"
      >
        <div class="card-icon overview">
          <span>📚</span>
        </div>
        <div class="card-content">
          <h4 class="card-title">全部分类</h4>
          <p class="card-count">{{ totalCount }}个文件</p>
        </div>
      </div>
      
      <!-- 知识分类卡片列表 -->
      <div 
        v-for="type in knoTypes" 
        :key="type.id"
        class="type-card"
        :class="{ active: selectedTypeId === type.id }"
        @click="selectType(type.id)"
      >
        <div class="card-icon" :class="getCardIconClass(type)">
          <span>{{ getCardIcon(type) }}</span>
        </div>
        <div class="card-content">
          <h4 class="card-title">{{ type.kno_type }}</h4>
          <p class="card-count">{{ type.knowledge_count || 0 }}个文件</p>
        </div>
        <div class="card-actions">
          <button 
            class="action-btn edit-btn" 
            @click.stop="editType(type)"
            title="编辑"
          >
            ✏️
          </button>
          <button 
            class="action-btn delete-btn" 
            @click.stop="deleteType(type.id)"
            title="删除"
          >
            🗑️
          </button>
        </div>
      </div>
    </div>

    <!-- 添加/编辑分类模态框 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h4>{{ showAddModal ? '添加知识分类' : '编辑知识分类' }}</h4>
          <button class="close-btn" @click="closeModal">✕</button>
        </div>
        
        <form @submit.prevent="submitForm" class="modal-form">
          <div class="form-group" v-if="showEditModal">
            <label for="knokinds_id">分类ID:</label>
            <input 
              id="knokinds_id"
              v-model="formData.knokinds_id" 
              type="text" 
              placeholder="分类ID"
              readonly
              class="readonly-input"
            />
            <small class="form-hint">分类ID不可修改</small>
          </div>
          
          <div class="form-group">
            <label for="kno_type">分类名称:</label>
            <input 
              id="kno_type"
              v-model="formData.kno_type" 
              @input="onKnoTypeChange"
              @blur="onKnoTypeChange"
              type="text" 
              placeholder="请输入分类名称"
              :class="{ 'error-input': formErrors.kno_type }"
              required
            />
            <div v-if="formErrors.kno_type" class="error-message">
              {{ formErrors.kno_type }}
            </div>
          </div>
          
          <div class="form-actions">
            <button type="button" class="btn-cancel" @click="closeModal">取消</button>
            <button type="submit" class="btn-submit" :disabled="loading">
              {{ loading ? '处理中...' : (showAddModal ? '添加' : '更新') }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 自定义确认框 -->
    <div v-if="showConfirm" class="custom-confirm-overlay" @click="handleConfirmNo">
      <div class="custom-confirm" @click.stop>
        <div class="confirm-icon">❓</div>
        <div class="confirm-content">
          <h3>{{ confirmMessage }}</h3>
        </div>
        <div class="confirm-buttons">
          <button class="confirm-btn cancel" @click="handleConfirmNo">取消</button>
          <button class="confirm-btn confirm" @click="handleConfirmYes">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getKnoTypes, createKnoType, updateKnoType, deleteKnoType } from '@/api/knoType'
import { getKnowledgeStats } from '@/api/knowledge'
import { generateUniqueKnokindsId } from '@/utils/tools/idGenerator'

// 响应式数据
const knoTypes = ref([])
const selectedTypeId = ref(null)
const showAddModal = ref(false)
const showEditModal = ref(false)
const loading = ref(false)
const totalCount = ref(0)
const knowledgeStats = ref({})

// 表单数据
const formData = ref({
  knokinds_id: '',
  kno_type: ''
})

// 编辑的类型
const editingType = ref(null)

// 表单验证状态
const formErrors = ref({
  kno_type: ''
})

// 确认框状态
const showConfirm = ref(false)
const confirmMessage = ref('')
const confirmCallback = ref(null)

// 计算属性
const selectedType = computed(() => {
  if (selectedTypeId.value === null) return null
  return knoTypes.value.find(type => type.id === selectedTypeId.value)
})

// 事件定义
const emit = defineEmits(['type-selected'])

// 方法
const loadKnoTypes = async () => {
  try {
    loading.value = true
    const response = await getKnoTypes()
    if (response.code === 200) {
      knoTypes.value = response.data || []
      // 加载文件统计信息
      await loadKnowledgeStats()
    } else {
      console.error('获取知识分类失败:', response.message)
    }
  } catch (error) {
    console.error('获取知识分类失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载文件统计信息
const loadKnowledgeStats = async () => {
  try {
    const response = await getKnowledgeStats()
    if (response.code === 200) {
      knowledgeStats.value = response.data || {}
      // 计算总数量
      totalCount.value = Object.values(knowledgeStats.value).reduce((sum, count) => sum + (count || 0), 0)
      
      // 更新每个分类的文件数量
      knoTypes.value.forEach(type => {
        type.knowledge_count = knowledgeStats.value[type.kno_type] || 0
      })
    } else {
      console.error('获取文件统计失败:', response.message)
      // 如果统计API失败，使用默认值
      knoTypes.value.forEach(type => {
        type.knowledge_count = 0
      })
      totalCount.value = 0
    }
  } catch (error) {
    console.error('获取文件统计失败:', error)
    // 如果统计API失败，使用默认值
    knoTypes.value.forEach(type => {
      type.knowledge_count = 0
    })
    totalCount.value = 0
  }
}

const selectType = (typeId) => {
  selectedTypeId.value = typeId
  emit('type-selected', typeId === null ? null : selectedType.value)
}

const editType = (type) => {
  editingType.value = type
  formData.value = {
    knokinds_id: type.knokinds_id,
    kno_type: type.kno_type
  }
  // 清除错误状态
  formErrors.value = {
    kno_type: ''
  }
  showEditModal.value = true
}

const openAddModal = () => {
  // 生成新的 knokinds_id
  formData.value = {
    knokinds_id: generateUniqueKnokindsId(),
    kno_type: ''
  }
  // 清除错误状态
  formErrors.value = {
    kno_type: ''
  }
  showAddModal.value = true
}

const deleteType = (typeId) => {
  const type = knoTypes.value.find(t => t.id === typeId)
  const typeName = type ? type.kno_type : '该分类'
  
  showCustomConfirm(`确定要删除知识分类"${typeName}"吗？`, async () => {
    try {
      loading.value = true
      const response = await deleteKnoType(typeId)
      if (response.code === 200) {
        await loadKnoTypes()
        // 如果删除的是当前选中的分类，重置选择
        if (selectedTypeId.value === typeId) {
          selectType(null)
        }
      } else {
        alert('删除失败: ' + response.message)
      }
    } catch (error) {
      console.error('删除知识分类失败:', error)
      alert('删除失败: ' + error.message)
    } finally {
      loading.value = false
    }
  })
}


const submitForm = async () => {
  // 验证表单
  const nameError = validateKnoTypeName(formData.value.kno_type)
  formErrors.value.kno_type = nameError
  
  if (nameError) {
    return // 如果有错误，不提交表单
  }
  
  try {
    loading.value = true
    let response
    
    if (showAddModal.value) {
      response = await createKnoType(formData.value)
    } else {
      response = await updateKnoType(editingType.value.id, formData.value)
    }
    
    if (response.code === 200) {
      await loadKnoTypes()
      closeModal()
    } else if (response.code === 403) {
      // 处理名称重复错误
      formErrors.value.kno_type = '该分类名称已存在'
    } else {
      alert((showAddModal.value ? '添加' : '更新') + '失败: ' + response.message)
    }
  } catch (error) {
    console.error('提交失败:', error)
    alert('操作失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 验证分类名称是否重复
const validateKnoTypeName = (name) => {
  if (!name || name.trim() === '') {
    return '分类名称不能为空'
  }
  
  // 检查是否与现有分类重名（编辑时排除自己）
  const existingType = knoTypes.value.find(type => 
    type.kno_type.toLowerCase() === name.toLowerCase() && 
    (!editingType.value || type.id !== editingType.value.id)
  )
  
  if (existingType) {
    return '该分类名称已存在'
  }
  
  return ''
}

// 实时验证分类名称
const onKnoTypeChange = () => {
  const error = validateKnoTypeName(formData.value.kno_type)
  formErrors.value.kno_type = error
}

// 显示确认框
const showCustomConfirm = (message, callback) => {
  confirmMessage.value = message
  confirmCallback.value = callback
  showConfirm.value = true
}

// 确认框处理
const handleConfirmYes = () => {
  if (confirmCallback.value) {
    confirmCallback.value()
  }
  showConfirm.value = false
}

const handleConfirmNo = () => {
  showConfirm.value = false
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  editingType.value = null
  formData.value = {
    knokinds_id: '',
    kno_type: ''
  }
  formErrors.value = {
    kno_type: ''
  }
}

// 获取卡片图标
const getCardIcon = (type) => {
  const iconMap = {
    '技术文档': '📁',
    '产品手册': '📋',
    '培训资料': '🎓',
    '设计文档': '🎨',
    '项目报告': '📊',
    '用户反馈': '💬',
    '会议记录': '📝',
    '规范文档': '📐'
  }
  return iconMap[type.kno_type] || '📁'
}

// 获取卡片图标样式类
const getCardIconClass = (type) => {
  const classMap = {
    '技术文档': 'tech',
    '产品手册': 'product',
    '培训资料': 'training',
    '设计文档': 'design',
    '项目报告': 'report',
    '用户反馈': 'feedback',
    '会议记录': 'meeting',
    '规范文档': 'standard'
  }
  return classMap[type.kno_type] || 'default'
}

// 刷新文件统计
const refreshStats = async () => {
  await loadKnowledgeStats()
}

// 暴露方法给父组件
defineExpose({
  refreshStats
})

// 生命周期
onMounted(() => {
  loadKnoTypes()
})
</script>

<style scoped>
.knowledge-type-navigation {
  margin-bottom: 1rem;
  color: var(--text-primary);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.navigation-header {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 1.2rem;
  padding-bottom: 0.5rem;
  flex-shrink: 0;
}

.new-category-btn {
  background: white;
  color: #374151;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  padding: 0.75rem 1.25rem;
  cursor: pointer;
  font-size: 0.875rem;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  box-shadow: none;
}

.new-category-btn:hover:not(:disabled) {
  background: #f9fafb;
  border-color: #9ca3af;
  transform: none;
  box-shadow: none;
}

.new-category-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-icon {
  font-size: 1rem;
}

.btn-text {
  font-weight: 500;
}

/* 卡片网格布局 */
.type-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
  flex: 1;
  overflow-y: auto;
  padding-right: 0.5rem;
}

/* 卡片样式 */
.type-card {
  background: white;
  border-radius: 0.375rem;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  border: 1px solid #d1d5db;
  box-shadow: none;
  display: flex;
  align-items: center;
  gap: 1rem;
}

.type-card:hover {
  transform: none;
  box-shadow: none;
  border-color: #9ca3af;
  background: #f9fafb;
}

.type-card.active {
  background: #f0f9ff;
  color: #1e40af;
  border-color: #3b82f6;
  box-shadow: none;
}

/* 卡片图标 */
.card-icon {
  width: 45px;
  height: 45px;
  border-radius: 0.375rem;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
  color: #6b7280;
}

.card-icon.overview {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.card-icon.tech {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.card-icon.product {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.card-icon.training {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.card-icon.design {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.card-icon.report {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.card-icon.feedback {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.card-icon.meeting {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.card-icon.standard {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

.card-icon.default {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
}

/* 卡片内容 */
.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.125rem;
}

.card-title {
  font-size: 0.875rem;
  font-weight: 600;
  margin: 0;
  color: #1e293b;
  line-height: 1.3;
}

.type-card.active .card-title {
  color: #1e40af;
}

.card-count {
  font-size: 0.75rem;
  color: #64748b;
  margin: 0;
  font-weight: 500;
}

.type-card.active .card-count {
  color: #3b82f6;
}

/* 卡片操作按钮 */
.card-actions {
  display: flex;
  gap: 0.5rem;
  opacity: 0;
  transition: opacity 0.2s ease;
  margin-left: auto;
}

.type-card:hover .card-actions {
  opacity: 1;
}

.action-btn {
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 0.25rem;
  padding: 0.25rem;
  cursor: pointer;
  font-size: 0.625rem;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 24px;
  height: 24px;
  color: #6b7280;
}

.action-btn:hover {
  background: #f9fafb;
  transform: none;
  border-color: #9ca3af;
}

.action-btn.edit-btn:hover {
  background: #f9fafb;
  border-color: #6b7280;
  color: #374151;
}

.action-btn.delete-btn:hover {
  background: #f9fafb;
  border-color: #6b7280;
  color: #374151;
}

.type-card.active .action-btn {
  background: white;
  border-color: #3b82f6;
  color: #1e40af;
}

.type-card.active .action-btn:hover {
  background: #f0f9ff;
  border-color: #1d4ed8;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease-out;
}

.modal-content {
  background: white;
  border-radius: 1rem;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
  width: 90%;
  max-width: 480px;
  max-height: 90vh;
  overflow: hidden;
  animation: slideIn 0.3s ease-out;
  border: 1px solid #e5e7eb;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 2rem;
  border-bottom: 1px solid #f3f4f6;
  background: #fafbfc;
}

.modal-header h4 {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.modal-header h4::before {
  content: "📁";
  font-size: 1.125rem;
}

.close-btn {
  background: #f3f4f6;
  border: none;
  font-size: 1rem;
  cursor: pointer;
  color: #6b7280;
  padding: 0.5rem;
  border-radius: 0.5rem;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #e5e7eb;
  color: #374151;
  transform: scale(1.05);
}

.modal-form {
  padding: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.75rem;
  font-weight: 600;
  color: #374151;
  font-size: 0.875rem;
  text-transform: uppercase;
  letter-spacing: 0.025em;
}

.form-group input {
  width: 100%;
  padding: 0.875rem 1rem;
  border: 2px solid #e5e7eb;
  border-radius: 0.5rem;
  background: #fafbfc;
  color: #1f2937;
  font-size: 0.875rem;
  transition: all 0.2s ease;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #3b82f6;
  background: white;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  transform: translateY(-1px);
}

.form-group input::placeholder {
  color: #9ca3af;
  font-style: italic;
}

.readonly-input {
  background: #f8fafc !important;
  color: #64748b !important;
  cursor: not-allowed !important;
  border-color: #e2e8f0 !important;
}

.readonly-input:focus {
  transform: none !important;
  box-shadow: none !important;
  border-color: #e2e8f0 !important;
}

.form-hint {
  display: block;
  margin-top: 0.5rem;
  font-size: 0.75rem;
  color: #64748b;
  font-style: italic;
}

.error-input {
  border-color: #ef4444 !important;
  background: #fef2f2 !important;
  color: #dc2626 !important;
}

.error-input:focus {
  border-color: #ef4444 !important;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1) !important;
  background: #fef2f2 !important;
}

.error-message {
  display: block;
  margin-top: 0.5rem;
  font-size: 0.75rem;
  color: #ef4444;
  font-weight: 500;
  animation: shake 0.3s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-2px); }
  75% { transform: translateX(2px); }
}

/* 自定义确认框样式 */
.custom-confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease-out;
}

.custom-confirm {
  background: white;
  border-radius: 0.75rem;
  padding: 2rem;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  animation: slideIn 0.3s ease-out;
  text-align: center;
}

.confirm-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  font-weight: bold;
  margin: 0 auto 1rem;
  background: #fef3c7;
  color: #d97706;
}

.confirm-content h3 {
  margin: 0 0 1.5rem 0;
  color: #374151;
  font-size: 1.125rem;
  font-weight: 500;
  line-height: 1.5;
}

.confirm-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.confirm-btn {
  border: none;
  border-radius: 0.5rem;
  padding: 0.75rem 2rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.confirm-btn.cancel {
  background: #f3f4f6;
  color: #374151;
}

.confirm-btn.cancel:hover {
  background: #e5e7eb;
}

.confirm-btn.confirm {
  background: #dc2626;
  color: white;
}

.confirm-btn.confirm:hover {
  background: #b91c1c;
  transform: translateY(-1px);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
  padding-top: 1.5rem;
  border-top: 1px solid #f3f4f6;
}

.btn-cancel, .btn-submit {
  padding: 0.875rem 2rem;
  border-radius: 0.5rem;
  font-weight: 600;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.btn-cancel {
  background: #f8fafc;
  color: #64748b;
  border: 2px solid #e2e8f0;
}

.btn-cancel:hover {
  background: #f1f5f9;
  border-color: #cbd5e1;
  color: #475569;
  transform: translateY(-1px);
}

.btn-submit {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  box-shadow: 0 4px 14px 0 rgba(59, 130, 246, 0.3);
}

.btn-submit:hover:not(:disabled) {
  background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px 0 rgba(59, 130, 246, 0.4);
}

.btn-submit:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 4px 14px 0 rgba(59, 130, 246, 0.2);
}


/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .knowledge-type-navigation {
    padding: 1rem;
  }
  
  .type-item {
    padding: 0.5rem;
  }
  
  .type-actions {
    opacity: 1;
  }
  
  .modal-content {
    width: 95%;
    margin: 1rem;
  }
  
  .modal-form {
    padding: 1.5rem;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .btn-cancel, .btn-submit {
    width: 100%;
  }
}
</style>
